package com.stenio.fancat.controller.shop;

import com.baomidou.mybatisplus.plugins.Page;
import com.stenio.fancat.controller.Result;
import com.stenio.fancat.domain.shop.FcRedOrder;
import com.stenio.fancat.domain.shop.FcShop;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.exception.FanCatException;
import com.stenio.fancat.form.shop.RedPacketOrderForm;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.service.behavior.BehaviorLogService;
import com.stenio.fancat.service.shop.SendRedPacketService;
import com.stenio.fancat.service.shop.ShopService;
import com.stenio.fancat.util.RedisUtil;
import com.stenio.fancat.vo.RedOrderVo;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liuan
 * @create 2019-01-30 16:44
 */
@RestController
@RequestMapping("red")
public class RedPacketController {

    @Autowired
    private SendRedPacketService sendRedPacket;

    @Autowired
    private ShopService shopService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private BehaviorLogService behaviorLogService;

    @Autowired
    private UserRelationshipMapper userRelationshipMapper;

    @Value("${key}")
    private String key;

    /**
     * 添加红包订单方法
     * @param fcRedOrder
     * @return
     */
    @PostMapping("add")
    public Result<FcRedOrder> add(@RequestBody FcRedOrder fcRedOrder) {
        Result result = new Result();
        FcRedOrder fc = null;
        try {
            fc = sendRedPacket.insert(fcRedOrder);
            String babyId = behaviorLogService.selectBabyId(fcRedOrder.getUserId());
            redisUtil.del(key+babyId);
            FcShop fcshop = shopService.getById(fcRedOrder.getBusinessId());
            redisUtil.del("shopGoods" + fcshop.getCategoryId(),"shopGoodsSingle"+fcshop.getId());
        } catch (FanCatException e) {
            result.setFlag(Result.FLAG.failure);
            result.setMsg(e.getMessage());
            return result;
        }
        result.setData(fc);
        return result;
    }

    @PostMapping("page")
    @ResponseBody
    public Result page(@RequestBody RedPacketOrderForm redPacketOrderForm){
        Result<Map<String,Object>> result = new Result();
        Page<FcRedOrder> page = sendRedPacket.selectByPage(redPacketOrderForm);
        Map<String,Object> data = new HashMap<>();
        if(page!=null){
            data.put("current",page.getCurrent());
            data.put("pages",page.getPages());
            data.put("size",page.getSize());
            data.put("total",page.getTotal());
            List<FcRedOrder> records = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(page.getRecords())){
                page.getRecords().stream().forEach(shop->{
                    records.add(redOrderToVo(shop));
                });
            }
            data.put("records",records);
        }
        result.setData(data);
        return result;
    }

    /**
     * 根据用户id查询红包订单方法
     * @param id
     * @return
     */
    @PostMapping("findRedOrder/{id}")
    public Result findRedOrder(@PathVariable String id) {
        Result result = new Result();
        List<FcRedOrder> fcRedOrders = sendRedPacket.selectRedOrder(id);
        Map<String,List> redOrders = new HashMap<>();
        SimpleDateFormat s = new SimpleDateFormat("yyyy年MM月dd日");
        if(CollectionUtils.isNotEmpty(fcRedOrders)) {
            for(FcRedOrder fcRedOrder : fcRedOrders) {
                String format = s.format(fcRedOrder.getCreateTime());
                if(redOrders.containsKey(format)) {
                    redOrders.get(format).add(redOrderToVo(fcRedOrder));
                }else {
                    List newList = new ArrayList<>();
                    newList.add(redOrderToVo(fcRedOrder));
                    redOrders.put(format,newList);
                }
            }
        }else {
            result.setFlag(Result.FLAG.failure);
            return result;
        }
        List orderList = new ArrayList();
        for(Map.Entry entry : redOrders.entrySet()) {
            Map newMap = new HashMap();
            newMap.put("dateTime",entry.getKey());
            newMap.put("order",entry.getValue());
            orderList.add(newMap);
        }
        result.setData(orderList);
        return result;
    }

    /**
     * 根据订单号查询商品详情
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @ResponseBody
    public Result get(@PathVariable String id){
        Result<RedOrderVo> result = new Result();
        FcRedOrder fcRedOrder = sendRedPacket.getById(id);
        if(fcRedOrder == null) {
            result.setFlag(Result.FLAG.failure);
            return result;
        }
        RedOrderVo redOrderVo = redOrderToVo(fcRedOrder);
        result.setData(redOrderVo);
        return result;
    }

    private RedOrderVo redOrderToVo(FcRedOrder fcRedOrder) {
        RedOrderVo redOrderVo = new RedOrderVo();
        BeanUtils.copyProperties(fcRedOrder,redOrderVo);
        FcShop fcShop = shopService.getById(fcRedOrder.getBusinessId());
        UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(fcRedOrder.getUserId());
        if(userRelationship != null) {
            redOrderVo.setUserName(userRelationship.getName());//TODO
        }
        redOrderVo.setWareName(fcShop.getName());
        return redOrderVo;
    }

}
